<template>
	<view>
		<view>
		    <RandomWheel :items="restaurantNearby" />
		  </view>
		<view>
		    <button @click="getLocation">获取当前位置</button>
		    <view>经度：{{ longitude }}</view>
		    <view>纬度：{{ latitude }}</view>
		  </view>
	</view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 经纬度
const latitude = ref(0)
const longitude = ref(0)

// 餐厅名称列表（只保留 title）
const restaurantNearby = ref<string[]>([])

// 封装 uni.request 用于 async/await
const uniRequest = (url: string) => {
  return new Promise<any>((resolve, reject) => {
    uni.request({
      url,
      method: 'GET',
      success: (res) => resolve(res.data),
      fail: (err) => reject(err),
    })
  })
}

// 获取附近餐厅数据（只保留 title）
const getNearbyRestaurants = async (lat: number, lng: number) => {
  const key = '3MDBZ-YWRK5-7I3IY-IRNQ6-KSROV-T6FTU'
  const keyword = '餐厅'
  const boundary = `nearby(${lat},${lng},200)`
  const url = `https://apis.map.qq.com/ws/place/v1/search?keyword=${keyword}&boundary=${boundary}&key=${key}&page_size=10`

  try {
    const res = await uniRequest(url)
    if (res.status === 0 && Array.isArray(res.data)) {
      restaurantNearby.value = res.data
        .slice(0, 10) // 限制10条
        .map((item: any) => item.title || '未命名餐厅')
    } else {
      uni.showToast({ title: '餐厅获取失败', icon: 'none' })
    }
  } catch (error) {
    console.error('请求餐厅失败:', error)
    uni.showToast({ title: '请求失败', icon: 'none' })
  }
}

// 获取位置
const getLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      latitude.value = res.latitude
      longitude.value = res.longitude
      console.log('当前位置（gcj02）:', res.latitude, res.longitude)
      getNearbyRestaurants(res.latitude, res.longitude)
    },
    fail: (err) => {
      console.error('getLocation 获取失败:', err)
      uni.showToast({ title: '定位失败', icon: 'none' })
    }
  })
}

// 检查权限并获取定位
const checkAndGetLocation = () => {
  uni.getSetting({
    success: (res) => {
      if (res.authSetting['scope.userLocation']) {
        getLocation()
      } else {
        uni.authorize({
          scope: 'scope.userLocation',
          success: () => {
            getLocation()
          },
          fail: () => {
            uni.showModal({
              title: '授权提醒',
              content: '请授权位置权限以获取附近餐厅',
              success: (res) => {
                if (res.confirm) {
                  uni.openSetting()
                }
              }
            })
          }
        })
      }
    },
    fail: () => {
      uni.showToast({ title: '权限检测失败', icon: 'none' })
    }
  })
}

onMounted(() => {
  checkAndGetLocation()
})
</script>

<style>

</style>
